package com.xyht.sca_s.student_manage_system.modules.wx.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUser;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserMapper;
import com.xyht.sca_s.student_manage_system.modules.wx.entity.ReplyMessageEntity;
import com.xyht.sca_s.student_manage_system.modules.wx.util.WeChatUtil;
import lombok.extern.log4j.Log4j2;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.xyht.sca_s.student_manage_system.modules.wx.constant.CommonConstant.BOOLEAN_FALSE;
import static com.xyht.sca_s.student_manage_system.modules.wx.constant.MsgTypeConstant.MSG_TYPE_TEXT;

@Service
@Log4j2
public class WXMpService {
    @Autowired
    private WeChatUtil weChatUtil;
    @Autowired
    private SmsUserMapper smsUserMapper;

    public void receiveUserPushEvent(HttpServletRequest request, PrintWriter pw) {
        try {
            String timestamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            String msgSignature = request.getParameter("msg_signature");
            Document doc = getDocument(request);
            String result2 = weChatUtil.decryptMsg(msgSignature, timestamp, nonce, doc.asXML());
            log.debug("解密后明文: " + result2);
            Map<String, String> map = docToMap(DocumentHelper.parseText(result2));
            String messageType = map.get("MsgType"); //这个值如果是event表示是事件推送；如果是其他字符，参照Test004
            String event = map.get("Event");
            String fromUserName = map.get("FromUserName");
            String toUserName = map.get("ToUserName");
            String content = map.get("Content");

            String stamp = System.currentTimeMillis() + "";
            ReplyMessageEntity replyMessageEntity = new ReplyMessageEntity();
            replyMessageEntity.setToUserName(fromUserName);
            replyMessageEntity.setFromUserName(toUserName);
            replyMessageEntity.setCreateTime(stamp);
            if (Objects.equals("event", messageType)) {
                //关注事件
                if (event.equals("subscribe")) {
                    replyMessageEntity.setMsgType(MSG_TYPE_TEXT);
                    replyMessageEntity.setContent("你好，欢迎关注SCDFJYJT！");

//                    replyMessageEntity.setMsgType(MSG_TYPE_NEWS);
//                    replyMessageEntity.setArticleCount(1);
//                    ReplyArticlesEntity articlesEntity = new ReplyArticlesEntity();
//                    List<ReplyItemEntity> item = new ArrayList<>();
//                    ReplyItemEntity replyItemEntity = new ReplyItemEntity();
//                    replyItemEntity.setDescription("星源消息通，可以接收所有星源慧通旗下产品实时消息，‘点击’本消息，快捷跳转消息绑定界面");
//                    replyItemEntity.setTitle("感谢您的关注！！");
//                    replyItemEntity.setPicUrl("https://xyht-software.com/xyht-sms/file/download?fileName=1685329540333.png");
//                    replyItemEntity.setUrl("https://ncdyeos.com/mpwx/enter");
//                    item.add(replyItemEntity);
//                    articlesEntity.setItem(item);
//                    replyMessageEntity.setArticles(articlesEntity);

                    //发送模板消息
//                    weChatUtil.sendWXMPTemplateMessage(fromUserName,"测试状态");
                } else if (event.equals("unsubscribe")) {
                    SmsUser updateUser = new SmsUser();
                    updateUser.setIsMessage(BOOLEAN_FALSE);
                    updateUser.setIsMpBind(BOOLEAN_FALSE);
                    updateUser.setWxMpId("");
                    smsUserMapper.update(updateUser, new QueryWrapper<SmsUser>()
                            .lambda()
                            .eq(SmsUser::getWxMpId, fromUserName));
                }

            }
            //公众号回复事件
            else if (Objects.equals("text", messageType)) {
                replyMessageEntity.setMsgType(MSG_TYPE_TEXT);
                replyMessageEntity.setContent("你好，欢迎关注SCDFJYJT！");

                //发送模板消息
//                weChatUtil.sendWXMPTemplateMessage(fromUserName,content);
            }

            String result = replyMessageEntity.toString();
            log.debug("++++++发送++++++++++" + result);
            String resultMsg = weChatUtil.encryptMsg(result, stamp + "", nonce);
            pw.write(resultMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private Map<String, String> docToMap(Document doc) {
        Map<String, String> map = new HashMap<String, String>();
        Element root = doc.getRootElement();
        @SuppressWarnings("unchecked")
        List<Element> list = root.elements();
        for (Element element : list) {
            map.put(element.getName(), element.getText());
        }
        return map;
    }

    private Document getDocument(HttpServletRequest request) {
        SAXReader reader = new SAXReader();
        try {
            InputStream ins = request.getInputStream();
            Document doc = reader.read(ins);
            return doc;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }
}
